package com.qfedu.so.service.impl;

import com.qfedu.common.param.OrderTblAdd;
import com.qfedu.common.vo.PageData;
import com.qfedu.common.vo.R;
import com.qfedu.so.dao.OrderTblDao;
import com.qfedu.so.entity.OrderTbl;
import com.qfedu.so.feign.AccountService;
import com.qfedu.so.feign.StorageService;
import com.qfedu.so.service.OrderTblService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * @program: Seata01
 * @description: 业务接口实现层，核心内容,类-OrderTblServiceImpl
 * @author: Feri
 * @create: 2024-11-15 08:29:51
 */
@Service
@RequiredArgsConstructor
public class OrderTblServiceImpl implements OrderTblService {

    private final OrderTblDao dao;
    private final StorageService storageService;
    private final AccountService accountService;

    /**
    * 新增订单
     * 入口
     * 内部涉及到了其他服务的操作*/
    @GlobalTransactional //开启全局事务 如果出现异常就回滚，没有异常就提交
    @Override
    public R save(OrderTblAdd add) {
        //涉及到其他服务 账户服务：查看余额、进行扣款 仓储服务：查询库存 扣减库存
        //生成订单
        //1.验证库存
        Integer storage=storageService.queryCount(add.getCommodityCode());
        if(storage<add.getCount()){
            return R.fail("亲，来晚了！库存不足！");
        }
        //2.验证账户余额
        Integer money=accountService.queryMoney(add.getUserId());
        if(money<add.getMoney()){
            return R.fail("亲，余额不足，请充值！");
        }

        //3.生成订单
        OrderTbl orderTbl=new OrderTbl();
        BeanUtils.copyProperties(add,orderTbl);
        orderTbl.setUserId(add.getUserId().toString());
        dao.insert(orderTbl);

        //4.库存扣减
        storageService.updateCount(add.getCommodityCode(),-add.getCount());
        //5.账户余额 扣减
        accountService.updateMoney(add.getUserId(),-add.getMoney());

        return R.ok("亲，下单成功啦！");
    }


    /**
    * 查询 所有数据*/
    @Override
    public R queryAll() {
        return R.ok(dao.selectList(null));
    }

}